package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceimpl  implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        log.info("请求微信接口，参数：appid={}, secret={}, js_code={}", weChatProperties.getAppid(), weChatProperties.getSecret(), userLoginDTO.getCode());

        log.info("开始进行用户登录：{}",userLoginDTO);

        //获得openid
        String openid = getOpenid(userLoginDTO.getCode());

        log.info("openid:{}",openid);

        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 3.判断是否为新用户
        User user = userMapper.getByOpenid(openid);

        //如果是新用户，则插入数据库

        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    private String getOpenid(String  code) {
        // 1.调用微信接口服务，获取openid和session_key
        Map<String, String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code", code);
        param.put("grant_type","authorization_code");
        String string = HttpClientUtil.doGet(WX_LOGIN_URL, param);
        // 2.解析微信接口返回数据
        JSONObject jsonObject = JSON.parseObject(string);
        String openid = jsonObject.getString("openid");
        log.info("微信接口返回数据：{}",string);
        return openid;
    }
}
